﻿using BCCommon;
using BCCommon.Enums;
using BCCommon.OAEnums;
using BCCommon.OAEnums.Attendance;
using BCCommon.OAEnums.Workflow;
using BCData.Common.Dictionary;
using BCData.OA.ApplyOrder;
using BCData.OA.Attendance.AttendanceRemedyApply;
using BCData.OA.CallbackMethodDictionary;
using BCData.OA.TeamWorks.TaskRecord;
using BCData.OA.TeamWorks.TaskRejectRecord;
using BCData.OA.Workflow.WorkflowActivityInstanceBusiness;
using BCData.OA.Workflow.WorkflowActivityInstanceReference;
using BCData.Sim.Admin.Admin;
using BCData.Sim.Admin.StaffOrganizationMappingRecord;
using BCData.Sim.Company.Company;
using BCData.Sim.Company.Department;
using BCDto.OA.Workflow.WorkflowActivityInstance;
using BCDto.OA.Workflow.WorkflowOperation;
using BCEntity.Common.Dictionary;
using BCEntity.OA.ApplyOrder;
using BCEntity.OA.TeamWorks.TaskRecord;
using BCService.OA.Workflow.WorkflowActivityInstanceBusiness;
using BCService.OA.WorkflowEngine.WorkflowRunning;
using System;
using System.Collections.Generic;
using System.Linq;

namespace BCService.OA.Workflow.AttendanceBusiness
{
    /// <summary>
    /// 考勤补考工作流服务
    /// </summary>
    public class RemedyCheckInWorkflowService : IRemedyCheckInWorkflowService
    {
        private readonly IApplicationContextService applicationContextService;
        private readonly IDictionaryReferenceData dictionaryReferenceData;
        private readonly ITaskRecordData taskRecordData;
        private readonly IDepartmentData departmentData;
        private readonly IApplyOrderData applyOrderData;
        private readonly IStaffOrganizationMappingRecordData staffOrganizationMappingRecordData;
        private readonly IAdminData adminData;
        private readonly IWorkflowActivityInstanceBusinessService workflowActivityInstanceBusinessService;
        private readonly IAttendanceRemedyApplyData attendanceRemedyApplyData;
        private readonly IWorkflowActivityInstanceReferenceData workflowActivityInstanceReferenceData;
        private readonly ITaskRejectRecordData taskRejectRecordData;
        private readonly ICallbackMethodDictionaryData callbackMethodDictionaryData;
        private readonly IWorkflowRunningService workflowRunningService;
        private readonly IWorkflowActivityInstanceBusinessData workflowActivityInstanceBusinessData;
        private readonly ICompanyData companyData;

        public RemedyCheckInWorkflowService(IApplicationContextService applicationContextService,
            IStaffOrganizationMappingRecordData staffOrganizationMappingRecordData,
            IAdminData adminData,
            IWorkflowActivityInstanceBusinessService workflowActivityInstanceBusinessService,
            IDepartmentData departmentData,
            IAttendanceRemedyApplyData attendanceRemedyApplyData,
            IWorkflowActivityInstanceReferenceData workflowActivityInstanceReferenceData,
            ITaskRejectRecordData taskRejectRecordData,
            ICallbackMethodDictionaryData callbackMethodDictionaryData,
            IApplyOrderData applyOrderData,
            IDictionaryReferenceData dictionaryReferenceData,
            IWorkflowRunningService workflowRunningService,
            IWorkflowActivityInstanceBusinessData workflowActivityInstanceBusinessData,
            ICompanyData companyData,
            ITaskRecordData taskRecordData)
        {
            this.applicationContextService = applicationContextService;
            this.taskRecordData = taskRecordData;
            this.workflowActivityInstanceBusinessService = workflowActivityInstanceBusinessService;
            this.departmentData = departmentData;
            this.adminData = adminData;
            this.staffOrganizationMappingRecordData = staffOrganizationMappingRecordData;
            this.attendanceRemedyApplyData = attendanceRemedyApplyData;
            this.workflowActivityInstanceReferenceData = workflowActivityInstanceReferenceData;
            this.taskRejectRecordData = taskRejectRecordData;
            this.callbackMethodDictionaryData = callbackMethodDictionaryData;
            this.applyOrderData = applyOrderData;
            this.dictionaryReferenceData = dictionaryReferenceData;
            this.workflowRunningService = workflowRunningService;
            this.workflowActivityInstanceBusinessData = workflowActivityInstanceBusinessData;
            this.companyData = companyData;
        }

        /// <summary>
        /// 初始化指派
        /// </summary>
        /// <param name="instanceDto"></param>
        /// <returns></returns>
        public bool InitAssign(WorkflowActivityInstanceDto instanceDto)
        {
            this.workflowActivityInstanceBusinessData.UpdateActivityStatus(instanceDto.WorkflowActivityInstanceId, ActivityInstanceStatus.Ongoing).GetAwaiter().GetResult();
            return this.AssignExecuterForPrincipalAdmin(instanceDto.WorkflowActivityInstanceId);
        }

        /// <summary>
        /// 初始化实例步骤
        /// </summary>
        /// <param name="instanceDto"></param>
        /// <returns></returns>
        public bool InitActivityStepInstanceAssign(WorkflowActivityInstanceDto instanceDto)
        {
            //IEnumerable<AttendanceAdminViewEntity> adminViewEntities = this.staffOrganizationMappingRecordData.GetAttendanceAdminView(instanceDto.CompanyId.Value).GetAwaiter().GetResult();
            //if (!adminViewEntities.Any())
            //{
            //    var companyEntity = this.companyData.GetMainCompanyEntity().GetAwaiter().GetResult();
            //    adminViewEntities = this.departmentStaffData.GetAttendanceAdminView(companyEntity.CompanyId).GetAwaiter().GetResult();
            //}
            //AttendanceAdminViewEntity adminViewEntity = null;
            var taskRecordEntity = this.MakeTask(instanceDto, instanceDto.CurrentlyStep);
            var step = instanceDto.Steps.First(s => s.TaskStep == instanceDto.CurrentlyStep);
            List<long> approvalAdminIds = new List<long>();
            //switch (step.AssignBased)
            //{
            //    case AssignBasedType.Department:
            //        if (!step.DepartmentId.HasValue)
            //        {
            //            throw new ArgumentException("请先设置指派部门。");
            //        }
            //        if (!adminViewEntities.Any(p => p.DepartmentId == step.DepartmentId))
            //        {
            //            var department = departmentData.GetById(step.DepartmentId.Value).GetAwaiter().GetResult();
            //            throw new ArgumentException($"公司没有{department.DepartmentName}，请先设置{department.DepartmentName}部门");
            //        }
            //        var viewList = adminViewEntities.Where(p => p.DepartmentId == step.DepartmentId.Value);
            //        int randomNumber = new Random().Next(0, viewList.Count() - 1);
            //        adminViewEntity = viewList.ElementAt(randomNumber);
            //        break;
            //    case AssignBasedType.Team:
            //        if (step.WorkingGroupId < 0)
            //        {
            //            throw new ArgumentException("指派工作组信息不存在。");
            //        }
            //        //TODO:人员和组没有绑定关系
            //        break;
            //    case AssignBasedType.Role:
            //        //角色逻辑未实现
            //        if (step.Role.IsNull())
            //        {
            //            throw new ArgumentException("指派角色信息不存在。");
            //        }
            //        //总经理特殊处理
            //        if (step.Role == "StaffRole_President")
            //        {
            //            var companyEntity = this.companyData.GetMainCompanyEntity().GetAwaiter().GetResult();
            //            var financeStaffConfigs = this.departmentStaffData.GetRoleStaffsAsync(step.Role, companyEntity.CompanyId).GetAwaiter().GetResult();
            //            if (!financeStaffConfigs.Any())
            //            {
            //                adminViewEntity = this.departmentStaffData.GetSuperAdmin(companyEntity.CompanyId).GetAwaiter().GetResult();
            //            }
            //            else
            //            {
            //                var viewRoleList = adminViewEntities.Where(p => p.Role.ToString() == step.Role);
            //                int tempRoleRandomNumber = new Random().Next(0, viewRoleList.Count() - 1);
            //                adminViewEntity = viewRoleList.ElementAt(tempRoleRandomNumber);
            //            }
            //        }
            //        else
            //        {
            //            var viewRoleList = adminViewEntities.Where(p => p.Role.ToString() == step.Role);
            //            int tempRoleRandomNumber = new Random().Next(0, viewRoleList.Count() - 1);
            //            adminViewEntity = viewRoleList.ElementAt(tempRoleRandomNumber);
            //        }
            //        break;
            //    case AssignBasedType.Human:
            //        if (!step.AdminId.HasValue)
            //        {
            //            throw new ArgumentException("请先设置指派人员。");
            //        }
            //        if (!adminViewEntities.Any(p => p.AdminId == step.AdminId))
            //        {
            //            var admin = adminData.GetAdmin(step.AdminId.Value).GetAwaiter().GetResult();
            //            throw new ArgumentException($"公司没有名为:{admin.FullName}的人员，请先设置该人员");
            //        }
            //        adminViewEntity = adminViewEntities.First(s => s.AdminId == step.AdminId);
            //        break;
            //    case AssignBasedType.Position:
            //        if (!adminViewEntities.Any(p => p.Position == step.Position))
            //        {
            //            string postionStr = ((OATaskBusinessType)Enum.Parse(typeof(OATaskBusinessType), step.Position)).GetDescriptionString();
            //            throw new ArgumentException($"公司没有{postionStr}岗位人员，请先设置岗位");
            //        }
            //        var viewPositionList = adminViewEntities.Where(p => p.Position == step.Position);
            //        int tempRandomNumber = new Random().Next(0, viewPositionList.Count() - 1);
            //        adminViewEntity = viewPositionList.ElementAt(tempRandomNumber);
            //        break;
            //    default:
            //        break;
            //}
            //if (adminViewEntity == null)
            //{
            //    throw new ArgumentException("考勤补卡相关申请指派人员失败。");
            //}
            //taskRecordEntity.TaskExecuterAdminId = adminViewEntity.AdminId;
            //taskRecordEntity.TaskExecuterFullName = adminViewEntity.FullName;
            //taskRecordEntity.RoleType = RoleType.Admin;
            //approvalAdminIds.Add(adminViewEntity.AdminId);
            if (!this.taskRecordData.UpdateStartTime(taskRecordEntity.TaskRecordNo, DateTime.Now).GetAwaiter().GetResult())
            {
                throw new ArgumentException(string.Format("更新任务执行人时失败,任务编号:{0}", taskRecordEntity.TaskRecordNo));
            }
            if (!this.taskRecordData.UpdateExecuterAdminInfo(taskRecordEntity).GetAwaiter().GetResult())
            {
                throw new ArgumentException(string.Format("更新任务执行人时失败,任务编号:{0}", taskRecordEntity.TaskRecordNo));
            }
            this.UpdateApplyOrderApprovalAdmin(taskRecordEntity);
            //TODO:推送未配置
            //pushMessageSendService.PushMessageForStaffApplication(staffName, taskRecordEntity.TaskExecuterAdminId.Value, PushMessageType.AttendanceRemedyCheckApplyNotify);
            return taskRecordEntity != null;
        }

        /// <summary>
        /// 任务通过
        /// </summary>
        /// <param name="instanceDto">活动实例</param>
        /// <param name="taskRecordEntity">任务信息</param>
        /// <param name="workflowOperationRequestDto">工作流操作信息</param>
        public void Pass(WorkflowActivityInstanceDto instanceDto, TaskRecordEntity taskRecordEntity, WorkflowOperationRequestDto workflowOperationRequestDto)
        {
            if (this.taskRecordData.UpdateHandleStatus(taskRecordEntity.TaskRecordNo, OATaskHandleStatus.Handled).GetAwaiter().GetResult())
            {
                if (instanceDto.CurrentlyStep == instanceDto.TotalStep - 1)
                {
                    var callbackEntity = this.callbackMethodDictionaryData.Get(instanceDto.WorkflowKey).GetAwaiter().GetResult();
                    applicationContextService.RequestServices.ExecuteMethod(callbackEntity.CallbackServiceName, callbackEntity.CallbackMethodName, callbackEntity.TaskName, instanceDto);
                }
                else
                {
                    if (this.workflowActivityInstanceBusinessData.UpdateWorkflowActivityCurrentlyStepNext(instanceDto.WorkflowActivityInstanceId).GetAwaiter().GetResult())
                    {
                        this.MakeTask(instanceDto, instanceDto.CurrentlyStep + 1);
                        this.workflowRunningService.Assigning(instanceDto.WorkflowActivityInstanceId);
                    }
                }
            }
        }

        /// <summary>
        /// 任务驳回
        /// </summary>
        /// <param name="instanceDto">活动实例</param>
        /// <param name="taskRecordEntity">任务信息</param>
        /// <param name="workflowOperationRequestDto">工作流操作信息</param>
        public void Reject(WorkflowActivityInstanceDto instanceDto, TaskRecordEntity taskRecordEntity, WorkflowOperationRequestDto workflowOperationRequestDto)
        {
            var taskRecords = this.taskRecordData.GetByWorkflowActivityInstanceIdAsync(instanceDto.WorkflowActivityInstanceId).GetAwaiter().GetResult();
            var lastTaskRecordEntity = taskRecords.OrderByDescending(p => p.CreateTime).First(p => p.CurrentlyStep == instanceDto.CurrentlyStep - 1);
            TaskRejectRecordEntity taskRejectRecordEntity = new TaskRejectRecordEntity()
            {
                TaskRecordNo = taskRecordEntity.TaskRecordNo,
                RejectRemark = workflowOperationRequestDto.Remark,
                WorkflowActivityInstanceId = instanceDto.WorkflowActivityInstanceId,
                RejectReceiverAdminId = lastTaskRecordEntity.TaskExecuterAdminId.Value,
                RejectReceiverAdminFullName = lastTaskRecordEntity.TaskExecuterFullName,
                RejectAdminId = taskRecordEntity.TaskExecuterAdminId.Value,
                RejectAdminFullName = taskRecordEntity.TaskExecuterFullName,
            };
            if (instanceDto.CurrentlyStep - 1 == 0)
            {
                this.taskRecordData.UpdateHandleStatus(taskRecordEntity.TaskRecordNo, OATaskHandleStatus.Dismissed).GetAwaiter().GetResult();
                var callbackEntity = this.callbackMethodDictionaryData.Get(instanceDto.WorkflowKey).GetAwaiter().GetResult();

                applicationContextService.RequestServices.ExecuteMethod(callbackEntity.CallbackServiceName, callbackEntity.CallbackMethodName, callbackEntity.TaskName, instanceDto);

                this.taskRejectRecordData.Add(taskRejectRecordEntity).GetAwaiter().GetResult();
            }
            else
            {
                this.taskRejectRecordData.Add(taskRejectRecordEntity).GetAwaiter().GetResult();
                if (this.taskRecordData.UpdateHandleStatus(taskRecordEntity.TaskRecordNo, OATaskHandleStatus.Dismissed).GetAwaiter().GetResult())
                {
                    if (this.workflowActivityInstanceBusinessData.UpdateWorkflowActivityCurrentlyStepPrevious(instanceDto.WorkflowActivityInstanceId).GetAwaiter().GetResult())
                    {
                        taskRecordEntity = this.MakeTask(instanceDto, instanceDto.CurrentlyStep - 1);
                        if (!this.taskRecordData.UpdateStartTime(taskRecordEntity.TaskRecordNo, DateTime.Now).GetAwaiter().GetResult())
                        {
                            throw new ArgumentException(string.Format("更新任务执行人时失败,任务编号:{0}", taskRecordEntity.TaskRecordNo));
                        }
                        this.taskRecordData.UpdateHandleStatus(taskRecordEntity.TaskRecordNo, OATaskHandleStatus.Rejected).GetAwaiter().GetResult();
                        this.workflowRunningService.Assigning(instanceDto.WorkflowActivityInstanceId);
                    }
                }
            }
        }

        /// <summary>
        /// 任务暂停
        /// </summary>
        /// <param name="instanceDto">活动实例</param>
        /// <param name="taskRecordEntity">任务信息</param>
        /// <param name="workflowOperationRequestDto">工作流操作信息</param>
        public void Paused(WorkflowActivityInstanceDto instanceDto, TaskRecordEntity taskRecordEntity, WorkflowOperationRequestDto workflowOperationRequestDto)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 任务关闭
        /// </summary>
        /// <param name="instanceDto">活动实例</param>
        /// <param name="taskRecordEntity">任务信息</param>
        /// <param name="workflowOperationRequestDto">工作流操作信息</param>
        public void Closed(WorkflowActivityInstanceDto instanceDto, TaskRecordEntity taskRecordEntity, WorkflowOperationRequestDto workflowOperationRequestDto)
        {
            throw new NotImplementedException();
        }

        #region 指派审核人为部门经理审批
        /// <summary>
        /// 指派审核人为部门经理审批
        /// </summary>
        /// <param name="workflowActivityInstanceId"></param>
        /// <returns></returns>
        public bool AssignExecuterForPrincipalAdmin(long workflowActivityInstanceId)
        {
            var instanceDto = this.workflowActivityInstanceBusinessService.GetInstanceInfo(workflowActivityInstanceId);
            var workflowActivityInstanceReference = workflowActivityInstanceReferenceData.Get(workflowActivityInstanceId).GetAwaiter().GetResult();
            if (workflowActivityInstanceReference.IsNotNull())
            {
                ApplyOrderEntity applyOrder = applyOrderData.GetByApplyOrderNoAsync(workflowActivityInstanceReference.ReferenceNo).GetAwaiter().GetResult();
                this.MakeTask(instanceDto, instanceDto.CurrentlyStep);
                var taskRecordEntity = this.taskRecordData.GetByWorkflowActivityInstanceIdAsync(workflowActivityInstanceId).GetAwaiter().GetResult().First(s => s.CurrentlyStep == instanceDto.CurrentlyStep);
                //var departmentStaff = departmentStaffData.GetByAdminIdAsync(applyOrder.AdminId).GetAwaiter().GetResult();
                //var department = departmentData.CheckPrincipalAdmin(applyOrder.AdminId).GetAwaiter().GetResult();
                //if (department != null)
                //{
                //    //寻找上一级部门负责人Id       
                //    var panrentDepartment = departmentData.GetById(department.ParentDepartmentId.Value).GetAwaiter().GetResult();
                //    if (panrentDepartment != null)
                //    {
                //        taskRecordEntity.TaskExecuterAdminId = panrentDepartment.PrincipalAdminId;
                //        taskRecordEntity.TaskExecuterFullName = panrentDepartment.DepartmentPrincipal;
                //    }
                //}
                //else
                //{
                //    var selfDepartment = departmentData.GetById(departmentStaff.DepartmentId).GetAwaiter().GetResult();
                //    taskRecordEntity.TaskExecuterAdminId = selfDepartment.PrincipalAdminId;
                //    taskRecordEntity.TaskExecuterFullName = selfDepartment.DepartmentPrincipal;
                //}
                taskRecordEntity.RoleType = RoleType.Admin;
                if (!this.taskRecordData.UpdateExecuterAdminInfo(taskRecordEntity).GetAwaiter().GetResult())
                {
                    throw new ArgumentException(string.Format("更新任务执行人时失败,任务编号:{0}", taskRecordEntity.TaskRecordNo));
                }
                if (!this.taskRecordData.UpdateStartTime(taskRecordEntity.TaskRecordNo, DateTime.Now).GetAwaiter().GetResult())
                {
                    throw new ArgumentException(string.Format("更新任务开始时间时失败,任务编号:{0}", taskRecordEntity.TaskRecordNo));
                }
                this.UpdateApplyOrderApprovalAdmin(taskRecordEntity, applyOrder);
                //TODO:推送未配置
                //pushMessageSendService.PushMessageForStaffApplication(staffName, item.TaskExecuterAdminId.Value, PushMessageType.AttendanceRemedyCheckApplyNotify);
                return taskRecordEntity != null;
            }
            return false;

        }

        private void UpdateApplyOrderApprovalAdmin(TaskRecordEntity taskRecordEntity, ApplyOrderEntity applyOrder = null)
        {
            if (applyOrder == null)
            {
                var workflowActivityInstanceReference = workflowActivityInstanceReferenceData.Get(taskRecordEntity.WorkflowActivityInstanceId).GetAwaiter().GetResult();
                if (workflowActivityInstanceReference.IsNotNull())
                {
                    applyOrder = applyOrderData.GetByApplyOrderNoAsync(workflowActivityInstanceReference.ReferenceNo).GetAwaiter().GetResult();
                }
            }
            List<long> approvalAdminIds = new List<long>
                {
                    taskRecordEntity.TaskExecuterAdminId.Value
                };
            //审批人赋值  
            if (applyOrder.ApprovalAdminIds.IsNotNull())
            {
                foreach (var item in applyOrder.ApprovalAdminIds.Split(','))
                {
                    long approvalId = long.Parse(item);
                    if (!approvalAdminIds.Any(s => s == approvalId))
                        approvalAdminIds.Add(approvalId);
                }
            }
            applyOrder.ModifierId = taskRecordEntity.TaskExecuterAdminId.Value;
            applyOrder.ModifierName = taskRecordEntity.TaskExecuterFullName;
            applyOrder.ApprovalAdminIds = string.Join(",", approvalAdminIds);
            applyOrderData.UpdateApprovalAdminIdsAsync(applyOrder).GetAwaiter().GetResult();
        }
        #endregion

        #region 构建步骤任务
        /// <summary>
        /// 创建任务
        /// </summary>
        /// <param name="instanceDto">活动实例</param>
        /// <param name="currentlyStep">当前步骤</param>
        /// <returns></returns>
        public TaskRecordEntity MakeTask(WorkflowActivityInstanceDto instanceDto, int currentlyStep)
        {
            var taskRecordEntities = this.taskRecordData.GetByWorkflowActivityInstanceIdAsync(instanceDto.WorkflowActivityInstanceId).GetAwaiter().GetResult();
            var taskRecords = taskRecordEntities.OrderByDescending(p => p.CreateTime);
            if (taskRecords.First().TaskExecuterAdminId.HasValue)
            {
                TaskRecordEntity taskRecordEntity = null;
                if (taskRecords.Any(p => p.CurrentlyStep == currentlyStep))
                {
                    taskRecordEntity = taskRecords.First(p => p.CurrentlyStep == currentlyStep);
                }
                else if (taskRecords.Count() == 1)
                {
                    taskRecordEntity = taskRecords.First();
                    taskRecordEntity.CurrentlyStep = currentlyStep;
                }
                else
                {
                    taskRecordEntity = taskRecords.First(p => p.CurrentlyStep == instanceDto.CurrentlyStep - 1);
                    taskRecordEntity.CurrentlyStep = currentlyStep;
                }
                taskRecordEntity.CompanyId = instanceDto.CompanyId.Value;
                this.AddTaskRecord(taskRecordEntity);
                return this.taskRecordData.GetLatestRecordAsync(instanceDto.WorkflowActivityInstanceId).GetAwaiter().GetResult();
            }
            else
            {
                return taskRecords.First();
            }
        }

        private void AddTaskRecord(TaskRecordEntity entity)
        {
            DictionaryReferenceEntity dictionaryReferenceEntity = this.dictionaryReferenceData.GetEntityAsync(entity.BusinessType).GetAwaiter().GetResult();

            TaskRecordEntity taskRecordEntity = new TaskRecordEntity()
            {
                TaskRecordNo = Guid.NewGuid().ToString(),
                BusinessType = dictionaryReferenceEntity.SearchKey,
                WorkflowActivityInstanceId = entity.WorkflowActivityInstanceId,
                TaskCategory = OATaskCategoryType.Business,
                BusinessTypeName = dictionaryReferenceEntity.ItemValue,
                RelevantTaskRecordNo = entity.RelevantTaskRecordNo,
                CurrentlyStep = entity.CurrentlyStep,
                TaskRemark = entity.TaskRemark,
                CompanyId = entity.CompanyId
            };
            this.taskRecordData.InsertAsync(taskRecordEntity);
        }
        #endregion

        #region 考勤补卡申请回调
        /// <summary>
        /// 考勤补卡申请完成后回调
        /// </summary>
        /// <param name="taskName"></param>
        /// <param name="instance"></param>
        public void RemedyCheckInCallback(string taskName, WorkflowActivityInstanceDto instance)
        {
            //修改工作流活动状态为Done。
            this.workflowActivityInstanceBusinessService.UpdateActivityStatus(instance.WorkflowActivityInstanceId, ActivityInstanceStatus.Done);
            //修改任务单状态为Done
            var workflowReference = workflowActivityInstanceReferenceData.Get(instance.WorkflowActivityInstanceId).GetAwaiter().GetResult();
            if (workflowReference.IsNotNull())
            {
                ApplyOrderEntity applyOrder = applyOrderData.GetByApplyOrderNoAsync(workflowReference.ReferenceNo).GetAwaiter().GetResult();
                var taskRecords = this.taskRecordData.GetByWorkflowActivityInstanceIdAsync(instance.WorkflowActivityInstanceId).GetAwaiter().GetResult();
                var lastTaskRecordEntity = taskRecords.OrderByDescending(p => p.CreateTime).First(p => p.CurrentlyStep == instance.CurrentlyStep);
                if (instance.CurrentlyStep - 1 == 0)
                {
                    applyOrder.Status = lastTaskRecordEntity.HandleStatus == OATaskHandleStatus.Dismissed ? OAApplyOrderStatus.Rejected : OAApplyOrderStatus.Done;
                    applyOrderData.UpdateStatusAsync(applyOrder).GetAwaiter().GetResult();
                    //修改考勤补卡申请信息为Done
                    var remedyApplyStatus = lastTaskRecordEntity.HandleStatus == OATaskHandleStatus.Dismissed ? RemedyApplyStatus.Rejected : RemedyApplyStatus.Done;
                    attendanceRemedyApplyData.UpdateStatus(applyOrder.ApplyCode, applyOrder.ModifierName, remedyApplyStatus, applyOrder.ModifierId).GetAwaiter().GetResult();
                }
                else
                {
                    applyOrder.ModifierId = lastTaskRecordEntity.TaskExecuterAdminId.Value;
                    applyOrder.Status = OAApplyOrderStatus.Done;
                    applyOrderData.UpdateStatusAsync(applyOrder).GetAwaiter().GetResult();
                    //修改考勤补卡申请信息为Done 
                    attendanceRemedyApplyData.UpdateStatus(applyOrder.ApplyCode, applyOrder.ModifierName, RemedyApplyStatus.Done, applyOrder.ModifierId).GetAwaiter().GetResult();
                }
            }

        }
        #endregion
    }
}

